package com.GlobalPaint.app.ui.Mine;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.Base.DialogWaiting;
import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.EventBusben;
import com.GlobalPaint.app.bean.MyFriendBean;
import com.GlobalPaint.app.bean.PostTalentBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.TalentBean;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.widget.CustomDatePicker1;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.GlobalPaint.app.R.id.ed_name;


public class ResumeActivity extends AppCompatActivity {
    private MyFriendBean myFriendBean;
    @BindView(R.id.iv_goback)
    ImageView ivGoback;
    @BindView(R.id.tv_common_center)
    TextView tvCommonCenter;
    @BindView(R.id.tv_fresh)
    TextView tvFresh;
    @BindView(ed_name)
    EditText edName;
    @BindView(R.id.et_education)
    TextView etEducation;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.et_birthdate)
    TextView etBirthdate;
    @BindView(R.id.et_post)
    EditText etPost;
    @BindView(R.id.et_salary)
    EditText etSalary;
    @BindView(R.id.tv_work)
    EditText tvWork;
    @BindView(R.id.tv_common)
    TextView tvCommon;
    @BindView(R.id.education)
    TextView education;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.email)
    TextView email;
    @BindView(R.id.birthdate)
    TextView birthdate;
    @BindView(R.id.post)
    TextView post;
    @BindView(R.id.salary)
    TextView salary;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.activity_resume)
    LinearLayout activityResume;
    @BindView(R.id.tv_zhuantai)
    TextView tvZhuantai;
    @BindView(R.id.et_sex)
    TextView etSex;
    @BindView(R.id.tv_guznzhu)
    TextView tvGuznzhu;
    private String now1;
    private String activity;//接受的数据 人才库  和 简历
    private Dialog dlgWaiting2;
    private TalentBean bean;
    private PostTalentBean postTalentBean;
    String posturl;
    String Remark;
    private String gqsj;
    private CustomDatePicker1 customDatePicker2;//开始时间
    String name;
    String gz;
    String jid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resume);
        ButterKnife.bind(this);
        initView();
        initDatePicker();
    }

    private void initView() {
        if (getIntent().getStringExtra("activity").equals("talent")) {
            ArrayList<String> infoList = new ArrayList<String>();
            infoList = getIntent().getStringArrayListExtra("infoList");
             name = infoList.get(0) == null ? "" : infoList.get(0);
            String Sex = infoList.get(1) == null ? "" : infoList.get(1);
            String Education = infoList.get(2) == null ? "" : infoList.get(2);
            String Phone = infoList.get(3) == null ? "" : infoList.get(3);
            String Email = infoList.get(4) == null ? "" : infoList.get(4);
            String Birthdate = infoList.get(5) == null ? "" : infoList.get(5);
            String Post = infoList.get(6) == null ? "" : infoList.get(6);
            String Salary = infoList.get(7) == null ? "" : infoList.get(7);
            String Work = infoList.get(8) == null ? "" : infoList.get(8);
            gz= infoList.get(10) == null ? "" : infoList.get(10);
            jid= infoList.get(11) == null ? "" : infoList.get(11);
            tvGuznzhu.setVisibility(View.VISIBLE);
            etEducation.setOnClickListener(null);
            etBirthdate.setOnClickListener(null);
            edName.setFocusable(false);
            etSex.setOnClickListener(null);
            etPhone.setFocusable(false);
            etEmail.setFocusable(false);
            etPost.setFocusable(false);
            etSalary.setFocusable(false);
            tvWork.setFocusable(false);
            edName.setText(name);
            if (Sex.equals("M")) {
                etSex.setText("男");
            } else {
                etSex.setText("女");
            }
            etEducation.setText(Education);
            if (Phone.length() > 4) {
                String phone1 = (Phone.substring(0, 3));
                String phone2 = Phone.substring(Phone.length() - 3, Phone.length());
                etPhone.setText(phone1 + "***" + phone2);
            }
            etEmail.setText(Email);
            if (Birthdate.length() > 10) {
                etBirthdate.setText(Birthdate.substring(0, 10));
            }

            etPost.setText(Post);
            etSalary.setText(Salary);
            tvWork.setText(Work);
            tvCommonCenter.setText("简历详情");
            if(gz.equals("true")){
                tvGuznzhu.setText("已关注");
            }else {
                tvGuznzhu.setText("关 注");
            }

        } else if (getIntent().getStringExtra("activity").equals("MineFragment")) {
            tvCommonCenter.setText("个人简历");
            tvFresh.setVisibility(View.VISIBLE);
            getReume();
        }

    }

    private void getReume() {
        dlgWaiting2 = DialogWaiting.createDialogWaiting(ResumeActivity.this, "加载中......");
        dlgWaiting2.show();
        String url = Constants.JASON_SERVICE_URL + "resume/query?fUserId=" + DataManager.userEntity.getUserId();
        DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), TalentBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                dlgWaiting2.cancel();
                bean = (TalentBean) o;
                if (bean.getStatus() == 1) {
                    if (bean.getData() != null && bean.getData().size() > 0) {
                        tvFresh.setText("编辑");
                        String name = bean.getData().get(0).getFName() ==
                                null ? "" : bean.getData().get(0).getFName();
                        String Sex = bean.getData().get(0).getFGender() ==
                                null ? "" : bean.getData().get(0).getFGender();
                        String Education = bean.getData().get(0).getFEducationExperience() ==
                                null ? "" : bean.getData().get(0).getFEducationExperience();
                        String Phone = bean.getData().get(0).getFMobile() ==
                                null ? "" : bean.getData().get(0).getFMobile();
                        String Email = bean.getData().get(0).getFEmail() ==
                                null ? "" : bean.getData().get(0).getFEmail();
                        String Birthdate = bean.getData().get(0).getFBirthDate() ==
                                null ? "" : bean.getData().get(0).getFBirthDate();
                        String Post = bean.getData().get(0).getFPost() ==
                                null ? "" : bean.getData().get(0).getFPost();
                        String Salary = bean.getData().get(0).getFExpectedSalary() ==
                                null ? "" : bean.getData().get(0).getFExpectedSalary();
                        String Work = bean.getData().get(0).getFWorkExperience() ==
                                null ? "" : bean.getData().get(0).getFWorkExperience();
                        String Remark = bean.getData().get(0).getFRemark() ==
                                null ? "0" : bean.getData().get(0).getFRemark();
                        edName.setText(name);
                        if (Sex.equals("M")) {
                            etSex.setText("男");
                        } else {
                            etSex.setText("女");
                        }
                        etEducation.setText(Education);
                        if (Phone.length() > 4) {
                            String phone1 = (Phone.substring(0, 3));
                            String phone2 = Phone.substring(Phone.length() - 3, Phone.length());
                            etPhone.setText(phone1 + "***" + phone2);
                        }
                        etEmail.setText(Email);
                        if (Birthdate.length() > 10) {
                            etBirthdate.setText(Birthdate.substring(0, 10));
                        }
                        if (Remark.equals("1")) {
                            tvZhuantai.setVisibility(View.VISIBLE);
                            tvZhuantai.setText("撤销");
                        } else if (Remark.equals("0")) {
                            tvZhuantai.setVisibility(View.VISIBLE);
                            tvZhuantai.setText("发布简历");
                        }
                        etPost.setText(Post);
                        etSalary.setText(Salary);
                        tvWork.setText(Work);

                    } else {
                        tvFresh.setText("新增");
                        tvZhuantai.setVisibility(View.GONE);
                    }
                } else {
                    Toast.makeText(ResumeActivity.this, bean.getMsg(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                dlgWaiting2.cancel();

                Toast.makeText(ResumeActivity.this, "获取失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    //选择时间
    private void initDatePicker() {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        now1 = sdf1.format(new Date());
        customDatePicker2 = new CustomDatePicker1(this, new CustomDatePicker1.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                gqsj = time + ":00";
                etBirthdate.setText(time);

            }
        }, "1950-01-01 00:00", "2030-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker2.showSpecificTime(true); // 显示时和分
        customDatePicker2.setIsLoop(true); // 允许循环滚动
    }

    //选择学历
    private void getEducation() {
        final String[] mlist = new String[]{"初中以下", "初中", "高中", "大专", "本科", "研究生", "博士", "博士后"};
        final ActionSheetDialog dialog = new ActionSheetDialog(ResumeActivity.this, mlist, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                etEducation.setText(mlist[position]);
                dialog.dismiss();
            }
        });
    }

    //选择学历
    private void sex() {
        final String[] mlist = new String[]{"男", "女"};
        final ActionSheetDialog dialog = new ActionSheetDialog(ResumeActivity.this, mlist, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                etSex.setText(mlist[position]);
                dialog.dismiss();
            }
        });
    }

    @OnClick({R.id.iv_goback, R.id.tv_fresh, R.id.tv_common, R.id.tv_zhuantai,
            R.id.et_birthdate, R.id.et_education, R.id.et_sex,R.id.tv_guznzhu})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_goback:
                finish();
                break;
            case R.id.tv_fresh:
                tvCommon.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_common:
                postResume();
                break;
            case R.id.tv_zhuantai:

                if (tvZhuantai.getText().toString().equals("发布简历")) {
                    Remark = "1";
                    postjianli();
                } else if (tvZhuantai.getText().toString().equals("撤销")) {
                    Remark = "0";
                    postjianli();
                }
                break;
            case R.id.et_birthdate:
                customDatePicker2.show(now1);
                break;
            case R.id.et_education:
                getEducation();
                break;
            case R.id.et_sex:
                sex();
                break;
            case R.id.tv_guznzhu:
                if(tvGuznzhu.getText().toString().equals("已关注")){
                    Toast.makeText(ResumeActivity.this,"已关注",Toast.LENGTH_LONG).show();
                    return;
                }
                String userName = DataManager.userEntity.getUserName();
                tianjiaHaoyou(userName,jid,name);
                break;
        }
    }

    public void tianjiaHaoyou(String userName, String jid, String nick){

        String url = Constants.JASON_SERVICE_URL + "appFriends/addAttention?userName=" + userName+
                "&jid="+jid+"&nick="+nick;
        DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), MyFriendBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                myFriendBean = (MyFriendBean) o;
                if (myFriendBean.getStatus() == 1) {
                    EventBusben baseMessage = new EventBusben("guanzhu");
                    EventBus.getDefault().post(baseMessage);
                    Toast.makeText(ResumeActivity.this, "添加成功", Toast.LENGTH_LONG).show();
                    finish();
                } else {
                    Toast.makeText(ResumeActivity.this, myFriendBean.getMsg(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {


            }
        });
    }
    private void postjianli() {
        String url = Constants.JASON_SERVICE_URL + "resume/revokestate?fUserId="
                + DataManager.userEntity.getUserId() + "&fRemark=" + Remark;

        DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), TalentBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                bean = (TalentBean) o;
                if (bean.getStatus() == 1) {
                    if (Remark.equals("0")) {
                        tvZhuantai.setVisibility(View.VISIBLE);

                        tvZhuantai.setText("发布简历");
                    } else {
                        tvZhuantai.setVisibility(View.VISIBLE);
                        tvZhuantai.setText("撤销");
                    }
                    Toast.makeText(ResumeActivity.this, "操作成功", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(ResumeActivity.this, bean.getMsg(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                Toast.makeText(ResumeActivity.this, "上传失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void postResume() {

        if (tvFresh.getText().toString().equals("新增")) {
            posturl = Constants.JASON_SERVICE_URL + "resume/save";
        } else if (tvFresh.getText().toString().equals("编辑")) {
            posturl = Constants.JASON_SERVICE_URL + "resume/update";
        }
        if (TextUtils.isEmpty(etPost.getText().toString())) {
            Toast.makeText(ResumeActivity.this, "请输入您的职位", Toast.LENGTH_LONG).show();
            return;
        }
        postTalentBean = new PostTalentBean();
        postTalentBean.setFName(edName.getText().toString());
        if(etSex.getText().toString().equals("男")){
            postTalentBean.setFGender("M");
        }else if(etSex.getText().toString().equals("女")){
            postTalentBean.setFGender("F");
        }
        postTalentBean.setFEducationExperience(etEducation.getText().toString());
        postTalentBean.setFMobile(etPhone.getText().toString());
        postTalentBean.setFEmail(etEmail.getText().toString());
        postTalentBean.setFBirthDate(etBirthdate.getText().toString() + ":00");
        postTalentBean.setFPost(etPost.getText().toString());
        postTalentBean.setFExpectedSalary(etSalary.getText().toString());
        postTalentBean.setFWorkExperience(tvWork.getText().toString());
        postTalentBean.setFUserId(DataManager.userEntity.getUserId());
        SimpleDateFormat nowqn = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String queen = nowqn.format(new Date());
        postTalentBean.setfCreationDate(queen);
        if (tvZhuantai.getText().toString().equals("发布简历")) {
            postTalentBean.setFRemark("0");
        } else {
            postTalentBean.setFRemark("1");
        }

        DataManager.getInst().postHttpRequestJsonClass(posturl, DataManager.userEntity.getCookie(), postTalentBean, TalentBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                bean = (TalentBean) o;
                if (bean.getStatus() == 1) {
                    Toast.makeText(ResumeActivity.this, "提交成功", Toast.LENGTH_LONG).show();
                    if (tvFresh.getText().toString().equals("新增")) {
                        tvCommon.setVisibility(View.VISIBLE);
                    } else {
                        tvCommon.setVisibility(View.GONE);
                    }
                } else {
                    Toast.makeText(ResumeActivity.this, bean.getMsg(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                Toast.makeText(ResumeActivity.this, "提交失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    //隐藏软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
